package com.szjz.rabbitmq.client.util;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.sun.istack.internal.NotNull;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author 史博
 * @desc MQ工具类
 * @date 2020/8/22 4:15 下午 周六
 */
@Slf4j
//@Configuration
public class RabbitMQUtils {

    private static ConnectionFactory connectionFactory;

    static {
        log.info("初始化链接工厂");
        // 创建mq的链接工厂对象
        connectionFactory = new ConnectionFactory();
        // 设置rabbitmq的主机ip
        connectionFactory.setHost("localhost");
        // 设置端口号
        connectionFactory.setPort(5672);
        // 设置链接的虚拟机
        connectionFactory.setVirtualHost("/");
        // 设置访问虚拟机的用户名和密码
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");

//        connectionFactory.setHost("10.106.11.37");
//        // 设置端口号
//        connectionFactory.setPort(5672);
//        // 设置链接的虚拟机
//        connectionFactory.setVirtualHost("/");
//        // 设置访问虚拟机的用户名和密码
//        connectionFactory.setUsername("guest");
//        connectionFactory.setPassword("guest");
    }


    /**
     * 获取链接
     */
    public static Connection getConnection() {
        // 获取链接对象
        Connection connection = null;
        try {
            connection = connectionFactory.newConnection();
            if (connection == null) {
                throw new RuntimeException();
            }
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 关闭连接
     */
    public static void close(@NotNull Connection connection, @NotNull Channel channel) {
        try {
            channel.close();
            connection.close();
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        }
    }
}
